"""
Case Type   : 兼容性--数据库兼容--B兼容--兼容语法--Load Data--公共函数
Case Name   : 兼容性--数据库兼容--B兼容--兼容语法--Load Data--公共函数
Create At   : 2023-5-30
Owner       : n@ningyali
Description :
    1、兼容性--数据库兼容--B兼容--兼容语法--Load Data--公共函数
Expect      :
    1、兼容性--数据库兼容--B兼容--兼容语法--Load Data--公共函数
History     :
"""
import os

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class LoadData:
    def __init__(self):
        self.log = Logger()
        self.constant = Constant()

    def create_data_file(self, node, case_num, *contant, f_type='txt'):
        cmd = ''
        for c in contant:
            f_path = os.path.join(
                '/home', node.ssh_user,
                f'{case_num}_{contant.index(c) + 1}.{f_type}')
            cmd += f'echo "{c}" > {f_path};'
        self.log.info(cmd)
        res = node.sh(cmd).result()
        self.log.info(res)
        if len(res.strip()) == 0:
            return True
        else:
            return False

    def create_b_db(self, node_sh, db_name):
        sql = f"drop database if exists {db_name};" \
            f"create database {db_name} dbcompatibility = 'B';" \
            f"\\c {db_name}"
        res = node_sh.execut_db_sql(sql)
        self.log.info(res)
        msg = f'You are now connected to database "{db_name}"'
        if self.constant.CREATE_DATABASE_SUCCESS in res and msg in res:
            return True
        else:
            return False

    def create_table(self, node_sh, db_name, t_name, cols,
                     attr_table='', suf_params='', detail=False):
        sql = f"drop table if exists {t_name};" \
            f"create {attr_table} table {t_name}({cols}) {suf_params};"
        res = node_sh.execut_db_sql(sql, dbname=db_name)
        self.log.info(res)
        if detail:
            return res
        else:
            if self.constant.CREATE_TABLE_SUCCESS in res:
                return True
            else:
                return False

    def create_schema(self, node_sh, db_name, schema_name, ):
        sql = f"drop schema if exists {schema_name};" \
            f"create schema {schema_name};"
        res = node_sh.execut_db_sql(sql, dbname=db_name)
        self.log.info(res)
        if self.constant.CREATE_SCHEMA_SUCCESS_MSG in res:
            return True
        else:
            return False

    def create_partition_table(self, node_sh, db_name, t_name, cols,
                               partition_by, partition_key, partitions,
                               pre_params='', suf_params=''):
        sql = f"drop table if exists {t_name};" \
            f"create table {t_name}({cols}) {pre_params} " \
            f"partition by {partition_by} ({partition_key}) {suf_params} " \
            f"({partitions});"
        res = node_sh.execut_db_sql(sql, dbname=db_name)
        self.log.info(res)
        if self.constant.CREATE_TABLE_SUCCESS in res:
            return True
        else:
            return False

    def load_data(self, node_sh, db_name, t_name, f_path, truncate=True,
                  alter='', encoding='sql_ascii', into_type='replace',
                  col_sep=',', col_end="''", line_start='#', line_end=";",
                  cols_name=None, escaped_by=None, fields='fields'):
        if truncate:
            sql = f"truncate table {t_name};"
        else:
            sql = ""
        sql += f"""{alter}
            load data infile '{f_path}'
            {into_type} into table {t_name} character set '{encoding}' 
            {fields} terminated by e'{col_sep}' enclosed by '{col_end}' 
            {f"escaped by '{escaped_by}'" if escaped_by else ''}
            lines starting by '{line_start}' terminated by '{line_end}' 
            {f'({cols_name})' if cols_name else ''};
            select * from {t_name};"""
        res = node_sh.execut_db_sql(sql, dbname=db_name)
        self.log.info(res)
        return res

    def clear_env(self, node_sh, node, db_name, f_path):
        text1 = '----删除兼容B库；expect:删除成功----'
        self.log.info(text1)
        res1 = node_sh.execut_db_sql(f"drop database if exists {db_name};")
        self.log.info(res1)

        text2 = '----删除数据文件；expect:删除成功----'
        self.log.info(text2)
        cmd = f'rm -rf {f_path}'
        self.log.info(cmd)
        res2 = node.sh(cmd).result()
        self.log.info(res2)

        if self.constant.DROP_DATABASE_SUCCESS in res1 and len(res2) == 0:
            return True
        else:
            return False
